package com.mengtian_tech.smart_lab.controller.console.attach;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import tool.ImageFileTools;

import com.mengtian_tech.smart_lab.entity.apply.ApplyForm;
import com.mengtian_tech.smart_lab.entity.cms.Attach;
import com.mengtian_tech.smart_lab.service.cms.AttachService;
import com.mengtian_tech.smart_lab.util.ImageUtils;

 

 
 
/**
 * 首页幻灯片管理
 * @author 王旭东
 *
 */
@Controller
@RequestMapping("/cms-attach")
public class AttachController {
	private Log log = LogFactory.getLog(getClass());
	 
	@Autowired
	SystemService systemService;
	@Autowired
	AttachService attachService;
	
	@RequestMapping(params="get")
	public void getById(@RequestParam("attachId")String attachId,HttpServletResponse resp) throws IOException{
		if(StringUtil.isEmpty(attachId)) return;
		Attach attach = systemService.getEntity(Attach.class, Long.parseLong(attachId));
		File file = ImageFileTools.findImgFile(attach.getFileName());
		FileInputStream fis = null;
		try {
			if (file != null) { 
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file); 
				int count = fis.read(buffer, 0, buffer.length);
				while (count > 0) {
					resp.getOutputStream().write(buffer, 0, count); 
					count = fis.read(buffer, 0, buffer.length);
				} 
			}

			resp.flushBuffer();

		} catch (Exception e) {
			log.error(e.getMessage(),e);
		} finally {
			if (fis != null){
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}  
	
	@RequestMapping(params = "upload")
	@ResponseBody
	public AjaxJson upload( HttpServletRequest request,
			@RequestParam(value="file",required=false) CommonsMultipartFile file) {
		
		try{ 
			Attach attach = null;
			if(file != null && !file.isEmpty()){
				File imgFile = ImageFileTools.saveFileFromInputStream("attach",file.getInputStream());
				attach = new Attach();
				attach.setOrigFileName(file.getOriginalFilename());
				attach.setFileType(file.getContentType());
				attach.setCreateDate(new Date());
				attach.setFileName("attach"+"/"+imgFile.getName());
				long attachId = (Long) systemService.save(attach);
				attach.setId(attachId);
				return AjaxJson.getSuccessResult(attachId+""); 
			} 
			return AjaxJson.getErrorResult();
		}catch(Exception e){
			e.printStackTrace(); 
			return AjaxJson.getErrorResult();
 		}
		
	} 

	@RequestMapping(params = "signUpload")
	@ResponseBody
	public AjaxJson signUpload( HttpServletRequest request,
			@RequestParam(value="Filedata",required=false) CommonsMultipartFile file,
			String ownerId) {
		
		try{ 
			Attach attach = null;
			if(file != null && !file.isEmpty()){
				File imgFile = ImageFileTools.saveSignFileFromInputStream("attach",file.getInputStream());
				
				attach = new Attach();
				attach.setOwnerId(ownerId);
				attach.setOrigFileName(file.getOriginalFilename());
				attach.setFileType(file.getContentType());
				attach.setCreateDate(new Date());
				attach.setFileName("attach"+"/"+imgFile.getName());
				long attachId = (Long) systemService.save(attach);
				attach.setId(attachId);
				
				ApplyForm form = systemService.getEntity(ApplyForm.class, ownerId);
				form.setSignAttachId(attachId);
				systemService.updateEntitie(form);
				
				return AjaxJson.getSuccessResult(attachId+""); 
			} 
			return AjaxJson.getErrorResult();
		}catch(Exception e){
			e.printStackTrace(); 
			return AjaxJson.getErrorResult();
 		}
		
	} 
	
	@RequestMapping(params="getByOwner")
	public void getByOwner(@RequestParam("ownerId")String id,HttpServletResponse resp) throws IOException{
		if(StringUtil.isEmpty(id)) return;
		List<Attach> attachList = attachService.findAttachByOwnerId(id);
		Attach attach;
		if(attachList.size() > 0){
			attach = attachList.get(0);
		}else{
			return;
		}
		File file = ImageFileTools.findImgFile(attach.getFileName());
		FileInputStream fis = null;
		try {
			if (file != null) { 
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file); 
				int count = fis.read(buffer, 0, buffer.length);
				while (count > 0) {
					resp.getOutputStream().write(buffer, 0, count); 
					count = fis.read(buffer, 0, buffer.length);
				} 
			}

			resp.flushBuffer();

		} catch (Exception e) {
			log.error(e.getMessage(),e);
		} finally {
			if (fis != null){
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}  
	
	@RequestMapping(params="getImg")
	public void getImg(@RequestParam("id")Long id,HttpServletResponse resp) throws IOException{
		Attach attach = systemService.getEntity(Attach.class, id);
		File file = ImageFileTools.findImgFile(attach.getFileName());
		FileInputStream fis = null;
		try {
			if (file != null) { 
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file); 
				int count = fis.read(buffer, 0, buffer.length);
				while (count > 0) {
					resp.getOutputStream().write(buffer, 0, count); 
					count = fis.read(buffer, 0, buffer.length);
				} 
			}

			resp.flushBuffer();

		} catch (Exception e) {
			log.error(e.getMessage(),e);
		} finally {
			if (fis != null){
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}  
	
	@RequestMapping(params="hasFile")
	@ResponseBody
	public AjaxJson hasFile(String ownerId){
		AjaxJson result = new AjaxJson();
		long count = systemService.getCountForJdbc("select count(*) from attach a where a.owner_id='" + ownerId + "'");
		if(count==0){
			result.setSuccess(false);
			result.setMsg("没有文件");
			return result;
		}
		return result;
		
	}
	
	@RequestMapping(params="download")
	public void download(String ownerId, HttpServletResponse response) throws IOException{
		List<Attach> attachs = attachService.findAttachByOwnerId(ownerId);
		for(Attach attach : attachs){
			Properties props = new Properties();
			props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
			String baseDir = props.getProperty("image_file_base_dir");
			String url = baseDir + "/" + attach.getFileName();
			File file = new File(url);
			response.reset();
            // 设置response的Header
			response.setHeader("content-disposition", "attachment;filename=" + new String(attach.getOrigFileName().getBytes()));  
			ImageFileTools.writeFileToOutpustStream(file,  response.getOutputStream());
		}
	}
}
